package p18.code;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;

public abstract class SocketUsingTask<T> implements CancelableTask<T> {

    private Socket socket;//套接字

    protected synchronized void setSocket(Socket s){
        socket = s;
    }

    public synchronized void cancel(){
        try{
            if(socket != null)
                socket.close();
        }catch(IOException ignored){

        }
    }

    public RunnableFuture<T> newTask() {
        return new FutureTask<T>(this) {
            public boolean cancel(boolean mayInterruptIfRunning){
                try{
                    SocketUsingTask.this.cancel();//将取消操作封装在任务的Future中
                }
                finally {
                    return super.cancel(mayInterruptIfRunning);
                }
            }
        };
    }

}
